import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/home/news_detail_logic.dart';
import 'package:ball_lion/entity/home/news_item_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/server/api/home_api.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/home/news_float2_widget.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:tencent_kit/tencent_kit.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';
// import 'package:tencent_kit/tencent_kit_platform_interface.dart';
// import 'package:wechat_kit/wechat_kit.dart';
// import 'package:weibo_kit/weibo_kit_platform_interface.dart';

class NewsShareAppend extends StatelessWidget {
  const NewsShareAppend(
      {super.key,
      required this.news,
      this.classId,
      this.collection,
      this.fuchuang});

  final shareItems = const [
    ['share_wx.png', '微信'],
    ['share_timeline.png', '朋友圈'],
    ['share_qq.png', 'QQ'],
    ['share_qqzone.png', 'QQ空间'],
    ['share_wb.png', '微博'],
    ['share_clipboard.png', '复制链接'],
  ];

  final NewsItemEntity news;
  final int? classId;

  final void Function()? collection;
  final void Function()? fuchuang;

  Future share(String name) async {
    final url = news.h5url ??
        "https://www.qiuxiangbiao.com/newsDetail?id=${news.id}&cid=$classId";

    final String title = news.title ?? "";
    String content = '看比分、看数据、看专家方案，就来球狮体育！';
    final File logo = await DefaultCacheManager().getSingleFile(
        'https://oss.qiuxiangbiao.com/prod/resource/qxb_logo.png');
    // String imageUri =
    //     'https://oss.qiuxiangbiao.com/prod/resource/qxb_logo.png';
    final ByteData bytes =
        await rootBundle.load(Utils.getImgPath('app_share_logo.png'));
    final Uint8List thumbImage = bytes.buffer.asUint8List();
    switch (name) {
      case '微信':
        Fluwx().share(WeChatShareWebPageModel(url,
            scene: WeChatScene.session,
            title: title,
            description: content,
            thumbData: thumbImage));
        break;
      case '朋友圈':
        Fluwx().share(WeChatShareWebPageModel(url,
            scene: WeChatScene.timeline,
            title: title,
            description: content,
            thumbData: thumbImage));
        break;
      case 'QQ':
        TencentKitPlatform.instance.shareWebpage(
            scene: TencentScene.kScene_QQ,
            title: title,
            summary: content,
            appName: '球狮体育',
            imageUri: Uri.file(logo.path),
            targetUrl: url);
        break;
      case 'QQ空间':
        TencentKitPlatform.instance.shareWebpage(
            scene: TencentScene.kScene_QZone,
            title: title,
            summary: content,
            appName: '球狮体育',
            imageUri: Uri.file(logo.path),
            targetUrl: url);
        break;
      // case '微博':
      //   WeiboKitPlatform.instance.shareWebpage(
      //       thumbData: thumbImage,
      //       title: title,
      //       description: content,
      //       webpageUrl: url);
      //   break;
      case '复制链接':
        Clipboard.setData(ClipboardData(text: url))
            .then((value) => Toast.text("已复制分享链接"));
        break;
      default:
    }

    //通知后台用户已分享新闻
    final id = news.id;
    if (id != null) {
      HomeApi.newsSupport(id, type: 3);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        _funcRow().marginSymmetric(horizontal: 20),
        const SizedBox(
          height: 24,
        ),
      ],
    );
    // return BottomSheet(
    //     backgroundColor: Colors.white,
    //     onClosing: () {},
    //     shape: const RoundedRectangleBorder(
    //         borderRadius: BorderRadius.vertical(top: Radius.circular(10))),
    //     clipBehavior: Clip.hardEdge,
    //     builder: (context) {
    //       return SafeArea(
    //         child: Column(
    //           mainAxisSize: MainAxisSize.min,
    //           crossAxisAlignment: CrossAxisAlignment.start,
    //           children: [
    //             const SizedBox(
    //               height: 24,
    //             ),
    //             if (news.h5url.hasValue) ...[
    //               _shareRow().marginSymmetric(horizontal: 20),
    //               const SizedBox(
    //                 height: 16,
    //               )
    //             ],
    //             _funcRow().marginSymmetric(horizontal: 20),
    //             const SizedBox(
    //               height: 24,
    //             ),
    //             Container(color: Colours.greyF7, height: 10),
    //             Container(
    //               height: 52,
    //               alignment: Alignment.center,
    //               child: QsText(
    //                 "取消",
    //                 style: TextStyle(color: Colours.grey99, fontSize: 17),
    //               ),
    //             ).tap(() {
    //               Get.back();
    //             }),
    //           ],
    //         ),
    //       );
    //     });
  }

  Widget _shareRow() => SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          // mainAxisAlignment: MainAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            ...shareItems.map((e) => _btn(e[0], e[1]).tap(() async {
                  await share(e[1]);
                  Get.back();
                }).marginOnly(right: 20))
          ],
        ),
      );

  Widget _funcRow() => Row(
        // mainAxisSize: MainAxisSize.min,
        children: [
          _btn(
                  news.collectId == 0
                      ? "news_collect_big.png"
                      : "news_collect_big1.png",
                  news.collectId == 0 ? "收藏" : "取消收藏")
              .tap(() {
            Get.back();
            Get.find<NewsDetailLogic>(tag: '${news.id}').onCollect();
          }).marginOnly(right: 20),
          _btn(
                  NewsFloat2Widget.existNews(news.id ?? 0)
                      ? "news_float_cancel.png"
                      : "news_float.png",
                  NewsFloat2Widget.existNews(news.id ?? 0) ? "取消浮窗" : "浮窗")
              .tap(() {
            Get.back();
            if (NewsFloat2Widget.existNews(news.id ?? 0)) {
              NewsFloat2Widget.delNews(news.id);
            } else {
              news.classId = classId ?? news.classId;
              NewsFloat2Widget.addNews(news).then((value) {});
            }
          }).marginOnly(right: 20),
          if (news.publisherId == User.info?.id && news.type == 2)
            _btn('news_delete.png', '删除').tap(() async {
              Get.back();
              final r = await Get.dialog(QsDialog.alert('确定要删除吗？'));
              if (r == true) {
                final result = await UserApi.deletePost(news.id!);
                if (result == 200) {
                  Toast.text('删帖成功');
                  Get.back();
                }
              }
            }).marginOnly(right: 20),
        ],
      );

  Widget _btn(String img, String name) {
    return Column(
      children: [
        Image.asset(Utils.getImgPath(img), width: 50, height: 50),
        const SizedBox(height: 4),
        QsText(
          name,
          color: Colours.grey66,
          fontSize: 12,
        )
      ],
    );
  }
}
